/**
 * 实行数据库事务
 */
package aorey.database;

import java.sql.SQLException;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import org.dom4j.DocumentException;
import aorey.database.config.DataConfigTransAction;
import aorey.nosql.EhcacheUtil;
import aorey.notice.Message;

public class DataBaseConfigTransactionAction extends DataBaseFactory {

	@SuppressWarnings({ "unused", "unchecked" })
	public Message actionTransaction(String id, HttpServletRequest request) {
		HashMap<String, String> dataCache = new HashMap<>();
		DataBaseTransactionReturnStruct baseTransactionReturnStruct;
		DataTag dataTag = new DataTag(request);
		DataTransactionConfigInfo dataTransactionConfigInfo = new DataTransactionConfigInfo(request);
		EhcacheUtil framework = (EhcacheUtil) request.getServletContext().getAttribute("aorey");
		HashMap<String, DataSource> dataBaseDrivers = (HashMap<String, DataSource>) framework.get("database",
				"drivers");
		DataBaseTransaction db = new DataBaseTransaction();
		DataConfigTransAction dataConfigTransAction;
		Message msg = new Message();
		try {
			dataConfigTransAction = dataTransactionConfigInfo.getTransaction(id);
//			System.out.println(dataConfigTransAction.dataSource);
			db.getConnection(dataBaseDrivers.get(dataConfigTransAction.dataSource).getConnection());
			int size = dataConfigTransAction.sqls.size();
			String recordID, rs;

			baseTransactionReturnStruct = db.transaction(dataConfigTransAction.sqls, request);
			if (baseTransactionReturnStruct.result == false) {
				msg.state = "10002";
				msg.error = baseTransactionReturnStruct.error;
			}
//			baseTransactionReturnStruct = db.transaction(dataConfigTransAction.sqls,request);

//			System.out.println("SQL Error:"+baseTransactionReturnStruct.error);
			db.close();
		} catch (DocumentException | SQLException e) {
			
			e.printStackTrace();
			msg.state = "10001";
			msg.error = e.getMessage();
		}

		return msg;
	}
}
